package com.yc.demo.d0730;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 拦截资源地址
@WebFilter({"*.s", "*.do"})
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("========= EncodingFilter init ===============");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        // 请求到达目标资源前, 执行的代码
        System.out.println("=========== doFilter before ==========");
        HttpServletRequest req = (HttpServletRequest) request;
        // 获取请求头参数 Accept
        // 设置 响应内容 字符集
        if (req.getHeader("Accept").startsWith("text/html")) {
            response.setContentType("text/html;charset=utf-8");
        } else if (req.getHeader("Accept").startsWith("application/json")
                || req.getHeader("Accept").startsWith("*/*")) {
            response.setContentType("application/json;charset=utf-8");
        }
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        chain.doFilter(request, response);
        // 请求到大目标资源后, 执行的代码
        System.out.println("=========== doFilter after ==========");
    }

    @Override
    public void destroy() {
        System.out.println("========= EncodingFilter destroy ===============");
    }
}
